﻿using System;
using System.Web.Mvc;
using System.Web;
using Hasiu.Service;

namespace Hasiu.Mvc.Filters
{
    public class AdminAuthorize : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            const string loginUrl = "/admin/login.aspx";
            if (filterContext.HttpContext.Request.Cookies["admin"] == null)
            {
                filterContext.Result = new RedirectResult(loginUrl);
                return;
            }
            try
            {
                var strArr = filterContext.HttpContext.Request.Cookies["admin"].Value.Decrypt().Split('|');
                if (strArr[0].ToDateTime() < DateTime.Now)
                {
                    filterContext.Result = new RedirectResult(loginUrl);
                    return;
                }
                var adminInfo = ConfigService._.GetAdminInfo();
                if (!adminInfo.UserName.Equals(strArr[1]) || !adminInfo.Password.Equals(strArr[2]))
                {
                    filterContext.Result = new RedirectResult(loginUrl);
                    return;
                }
            }
            catch
            {
                filterContext.Result = new RedirectResult(loginUrl);
                return;
            }
        }
    }
}
